import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@stores'

/**
 * createWebHistory(import.meta.env.BASE_URL) 表示访问本项目视图组件时会自动携带的前缀
 * 例如原本默认 / ，那么 localhost/home,localhost/list
 * 如果 createWebHistory('/jd')，则访问 list 视图时：localhost/jd/list
 * 该特性可配合 nginx 做前端项目代理
 */
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path:'/login', component: () => import('@/views/login/LoginPage.vue')},
    { 
      path:'/', // 跳转到主页时自动重定向到 ArticleManager
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manager',
      children: [
        {
          path:'/article/manager',
          component: () => import('@/views/article/ArticleManager.vue'),
        },
        {
          path:'/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue'),
        },
        {
          path:'/user/profile',
          component: () => import('@/views/user/UserProfile.vue'),
        },
        {
          path:'/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue'),
        },
        {
          path:'/user/Password',
          component: () => import('@/views/user/UserPassword.vue'),
        }
      ]
    },
  ],
})

router.beforeEach(to => {
  const userStore = useUserStore()
  if(!userStore.token && to.path !== '/login'){
    return '/login'
  }
  return true
})

export default router
